package test.demo.support;


import cn.hutool.core.bean.BeanUtil;
import cn.jc.springframework.beans.factory.config.BeanReference;
import test.demo.BeansException;
import test.demo.PropertyValue;
import test.demo.PropertyValues;
import test.demo.config.BeanDefinition;

import java.lang.reflect.Constructor;

/**
 * @Description:
 * @author: JC
 * @date: 2023/4/4 23:05
 */
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory{

    private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();


    @Override
    protected Object createBean(String name, BeanDefinition beanDefinition,Object[] args) throws BeansException {
        Object bean;
        try {
            if(args == null){
                bean = beanDefinition.getBeanClass().newInstance();
            }else{
                bean = createBeanInstance(beanDefinition, name, args);
            }
            applyPropertyValues(name, bean, beanDefinition);
        } catch (InstantiationException | IllegalAccessException e) {
            throw new BeansException("Instantiation of bean failed",e);
        }

        addSingleton(name, bean);
        return bean;
    }

    protected  void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition){
        PropertyValues propertyValues = beanDefinition.getPropertyValues();

        try {
            for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
                String name = propertyValue.getName();
                Object value = propertyValue.getValue();
                if (value instanceof BeanReference) {
                    BeanReference beanReference = (BeanReference) value;
                    value = getBean(beanReference.getBeanName());
                }
                BeanUtil.setFieldValue(bean,name,value);
            }
        } catch (BeansException e) {
            throw new BeansException("Error setting property values：" + beanName);
        }

    }

    protected Object createBeanInstance(BeanDefinition beanDefinition, String beanName
            , Object[] args) {
        Constructor[] constructors = beanDefinition.getBeanClass().getConstructors();
        Constructor constructorToUse = null;
        for (Constructor constructor : constructors) {
            if(args == null && constructor.getParameterTypes().length == args.length){
                constructorToUse = constructor;
                break;
            }
        }
        return instantiationStrategy.instantiate(beanDefinition, beanName, constructorToUse ,args);
    }


    public InstantiationStrategy getInstantiationStrategy(){
        return this.instantiationStrategy;
    }
    public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy){
        this.instantiationStrategy = instantiationStrategy;
    }
}
